<template>
  <div class="app-container">
    <el-form :inline="true" :model="queryParams" ref="queryRef" label-width="80px">
      <el-form-item label="学员">
        <el-select v-model="queryParams.studentId" filterable remote clearable placeholder="选择学员"
          :remote-method="searchStudents" :loading="loadingStudents" style="width:220px" @visible-change="onStudentVisible">
          <el-option v-for="s in studentOptions" :key="s.studentId" :label="s.name + '（' + s.studentNo + '）'" :value="s.studentId" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="queryParams.feeTypeId" clearable placeholder="费用类型">
          <el-option v-for="t in feeTypeOptions" :key="t.feeTypeId" :label="t.feeName" :value="t.feeTypeId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['jiaxiao:payment:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete()" v-hasPermi="['jiaxiao:payment:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" :row-key="getRowId">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="paymentId" width="100" />
      <el-table-column label="学员" prop="studentId" :formatter="fmtStudent" width="180" />
      <el-table-column label="类型" prop="feeTypeId" :formatter="fmtFeeType" width="140" />
      <el-table-column label="金额" prop="amount" width="120" />
      <el-table-column label="时间" prop="paidAt" width="180" />
      <el-table-column label="状态" prop="status" width="120" />
      <el-table-column label="操作人" prop="operator" width="120" />
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-card class="mt16">
      <div>学员总已支付：{{ totalPaid }}</div>
    </el-card>

    <el-dialog :title="title" :visible.sync="open" width="600px">
      <el-form ref="formRef" :model="form" label-width="120px">
        <el-form-item label="学员">
          <el-select v-model="form.studentId" filterable remote clearable placeholder="选择学员"
            :remote-method="searchStudents" :loading="loadingStudents" style="width:100%" @visible-change="onStudentVisible">
            <el-option v-for="s in studentOptions" :key="s.studentId + '_f'" :label="s.name + '（' + s.studentNo + '）'" :value="s.studentId" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.feeTypeId" placeholder="类型" style="width:100%">
            <el-option v-for="t in feeTypeOptions" :key="t.feeTypeId" :label="t.feeName" :value="t.feeTypeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额">
          <el-input-number v-model="form.amount" :min="0" :step="50" />
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker v-model="form.paidAt" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择时间" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="已支付" value="已支付" />
            <el-option label="待支付" value="待支付" />
            <el-option label="已退款" value="已退款" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open=false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPayment, addPayment, updatePayment, delPayment, sumPaid } from '@/api/jiaxiao/payment'
import { listFeeType } from '@/api/jiaxiao/feeType'
import { listStudent, getStudent } from '@/api/jiaxiao/student'

export default {
  name: 'JxPayment',
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      list: [],
      multiple: true,
      ids: [],
      selectedRows: [],
      totalPaid: 0,
      queryParams: { pageNum: 1, pageSize: 10, studentId: undefined, feeTypeId: undefined },
      title: '',
      open: false,
      form: { status: '已支付', paidAt: undefined },
      feeTypeOptions: [],
      studentOptions: [],
      loadingStudents: false,
      studentMap: {},
      feeTypeMap: {}
    }
  },
  created() {
    this.getList();
    listFeeType({ status: '0' }).then(res => { this.feeTypeOptions = res.rows || []; this.feeTypeMap = Object.fromEntries(this.feeTypeOptions.map(t=>[t.feeTypeId, t.feeName])) })
  },
  methods: {
    getRowId(row){ return row && (row.paymentId || row.id || row.paymentID || row.PAYMENT_ID) },
    getList() {
      this.loading = true
      listPayment(this.queryParams).then(res => {
        const rows = res.rows || []
        this.list = rows.map(r => ({ ...r, id: r.paymentId }))
        this.total = res.total; this.loading = false;
        if (this.queryParams.studentId) this.refreshSum(this.queryParams.studentId);
        this.buildStudentMapForList();
      })
    },
    async buildStudentMapForList(){
      const ids = Array.from(new Set((this.list||[]).map(x=>x.studentId).filter(Boolean)))
      for (const id of ids){
        if (!this.studentMap[id]){
          try { const { data } = await getStudent(id); if (data) this.$set(this.studentMap, id, data.name) } catch(e) {}
        }
      }
    },
    refreshSum(studentId) { sumPaid(studentId).then(res => { this.totalPaid = res.data || 0 }) },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    resetQuery() { this.$refs.queryRef && this.$refs.queryRef.resetFields(); this.handleQuery() },
    handleSelectionChange(selection) {
      try { console.log('[payment] selection-change selection=', selection) } catch(e) {}
      this.selectedRows = selection
      this.ids = (selection||[]).map(i => this.getRowId(i)).filter(v => v !== undefined && v !== null && v !== '')
      try { console.log('[payment] mapped ids=', this.ids) } catch(e) {}
      this.multiple = !selection.length
    },
    handleAdd() { this.title = '新增缴费'; this.form = { status: '已支付' }; this.open = true },
    submitForm() { const req = this.form.paymentId ? updatePayment(this.form) : addPayment(this.form); req.then(() => { this.$message.success('保存成功'); this.open = false; this.getList() }) },
    handleDelete(row) {
      try { console.log('[payment] handleDelete row=', row, 'ids(state)=', this.ids, 'selectedRows=', this.selectedRows) } catch(e) {}
      const ids = row ? [this.getRowId(row)] : (this.ids && this.ids.length ? this.ids : (this.selectedRows || []).map(r => this.getRowId(r)))
      const idsStr = (ids || []).filter(Boolean).join(',')
      try { console.log('[payment] computed idsStr=', idsStr) } catch(e) {}
      if (!idsStr) { this.$message.warning('请选择要删除的记录'); return }
      this.$modal.confirm('确认删除选中记录吗？')
        .then(() => delPayment(idsStr))
        .then(() => { this.$message.success('删除成功'); this.getList() })
    },
    onStudentVisible(v){ if(v && this.studentOptions.length===0) this.searchStudents('') },
    searchStudents(q){ this.loadingStudents=true; listStudent({ pageNum:1, pageSize:10, name:q }).then(res=>{ this.studentOptions=res.rows||[]; this.loadingStudents=false; this.studentMap = Object.fromEntries(this.studentOptions.map(s=>[s.studentId, s.name])); }).catch(()=>{ this.loadingStudents=false }) },
    fmtStudent(row){ return this.studentMap[row.studentId] || row.studentId },
    fmtFeeType(row){ return this.feeTypeMap[row.feeTypeId] || row.feeTypeId }
  }
}
</script>

<style scoped>
.mt16 { margin-top: 16px; }
.mb8 { margin-bottom: 8px; }
</style>


